import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'
import { AjaxService, Req, Res } from "./ajax.service"
import { Day } from './day'
import { Daily } from './daily'
import { User } from './user'
import { UserService } from './user.service'
import { Task } from './task'
import { TaskService } from './task.service'
import { DailyService } from './daily.service'
import * as moment from 'moment';

@Component({
  selector: 'app-daily',
  templateUrl: './daily.component.html',
  styleUrls: ['./daily.component.css']
})
export class DailyComponent implements OnInit {

	mine: User
  tasks: Array<Task>
  daily: Daily = new Daily()
  dailyShowed: boolean
  day: Day
  current_date: string
  date: string
  bh = AjaxService.APIROOT + '/dailys';

  constructor(private userService: UserService,
              private taskService: TaskService,
               private dailyService: DailyService,
              private router: Router) { }

  ngOnInit() {
      moment.locale('en', {
      weekdays : [
          "星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"
      ]
    });

     
  	 this.userService.getUserMine().then(user => {
      if (!user) return false
      this.mine = user
    })

  }

  onCalendarSelected(sel_days: Array<Day>): void {
    this.changeShowDate(sel_days[0])
  }

  changeShowDate(day: Day) {
    this.day = day 
    var date = `${day.y}-${day.m + 1}-${day.num}`
    var argv = { date: date}
    this.date =date
    this.current_date = moment(date).format("YYYY年MM月DD日 dddd")
    this.dailyService.list(argv).then(tasks => this.inittask(tasks))
  }

  inittask(tasks: Array<Task>): void {
     this.tasks = tasks.filter(task => {
       task.dailys.filter(daily => {
         daily.date = moment(daily.date).format("YYYY年MM月DD日 dddd")
         return daily
       })
       return task
     })
  }


   createdaily(daily): void {
    this.dailyShowed = true
    this.dailyService.get(daily.id).then(daily => this.daily = daily)
  }

  save(daily): void {
    /*this.daily.report = this.daily.report.replace('\n','<br/>')
    this.daily.next_work = this.daily.next_work.replace('\n','<br/>')*/
    this.dailyService.save(this.daily).then(res => {
      if (res.error) {
        if (res.error == "TOKEN-ERROR")
          return alert("无法处理，需要登录")
        return alert("出现错误，" + (res.msg || res.error))
      }
      this.dailyShowed = false
      daily => this.daily = daily
      this.changeShowDate(this.day)
      
    })
  }

   export(): void {
    var token = localStorage.getItem("token")
    window.location.href = this.bh + '/list.xls?token='+ token +'&date='+ this.date
  }

}
